package com.project.demo.controller;

import com.project.demo.entity.UserAccommodation;
import com.project.demo.entity.User;
import com.project.demo.service.UserAccommodationService;
import com.project.demo.service.SmsService;
import com.project.demo.service.UserService;
import com.project.demo.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用户住宿：(UserAccommodation)表控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("/user_accommodation")
public class UserAccommodationController extends BaseController<UserAccommodation, UserAccommodationService> {

    /**
     * 用户住宿对象
     */
    @Autowired
    public UserAccommodationController(UserAccommodationService service) {
        setService(service);
    }

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserService userService;

    @Autowired
    private com.project.demo.service.MessageNotificationService messageNotificationService;


    @PostMapping("/add")
    @Transactional
    public Map<String, Object> add(HttpServletRequest request) throws IOException {
        Map<String,Object> paramMap = service.readBody(request.getReader());
        this.addMap(paramMap);
        
        // 自动创建消息通知
        try {
            Integer accommodationId = null;
            Integer userId = null;
            
            // 从参数中获取用户ID
            if (paramMap.get("participants") != null) {
                userId = Integer.parseInt(paramMap.get("participants").toString());
            }
            
            // 从参数中获取主键ID（如果存在，说明是更新操作；如果不存在，需要查询刚插入的记录）
            if (paramMap.get("user_accommodation_id") != null) {
                accommodationId = Integer.parseInt(paramMap.get("user_accommodation_id").toString());
            } else {
                // 如果是新增操作，需要查询刚插入的记录ID
                // 使用更精确的查询条件：participants + 其他关键字段的组合
                Map<String, String> query = new HashMap<>();
                if (userId != null) {
                    query.put("participants", userId.toString());
                }
                // 添加其他唯一字段来确保查询到正确的记录
                if (paramMap.get("conference_name") != null) {
                    query.put("conference_name", paramMap.get("conference_name").toString());
                }
                if (paramMap.get("accommodation_location") != null) {
                    query.put("accommodation_location", paramMap.get("accommodation_location").toString());
                }
                Map<String, String> config = new HashMap<>();
                config.put("order", "create_time desc");
                config.put("size", "1");
                Query select = service.select(query, config);
                Object resultObj = select != null && select.getResultList().size() > 0 ? select.getResultList().get(0) : null;
                
                if (resultObj instanceof UserAccommodation) {
                    UserAccommodation accommodation = (UserAccommodation) resultObj;
                    accommodationId = accommodation.getUser_accommodation_id();
                }
            }
            
            // 如果找到了记录ID，创建消息通知
            // 优先使用 paramMap 中的值（这些是前端提交的实际数据）
            if (accommodationId != null && userId != null) {
                String conferenceName = paramMap.get("conference_name") != null ? paramMap.get("conference_name").toString() : null;
                String accommodationLocation = paramMap.get("accommodation_location") != null ? paramMap.get("accommodation_location").toString() : null;
                String accommodationNo = paramMap.get("accommodation_no") != null ? paramMap.get("accommodation_no").toString() : null;
                String userName = paramMap.get("user_name") != null ? paramMap.get("user_name").toString() : null;
                
                messageNotificationService.createAccommodationMessage(
                    userId,
                    accommodationId,
                    conferenceName,
                    accommodationLocation,
                    accommodationNo,
                    userName
                );
            }
        } catch (Exception e) {
            log.error("创建住宿消息通知失败", e);
        }
        
        return success(1);
    }

    /**
     * 发送住宿通知短信
     */
    @PostMapping("/send_sms")
    public Map<String, Object> sendSms(HttpServletRequest request) {
        try {
            // 先尝试从请求体读取（POST数据）
            Map<String, Object> bodyMap = null;
            try {
                bodyMap = service.readBody(request.getReader());
            } catch (Exception e) {
                log.debug("读取请求体失败，尝试从查询参数读取: {}", e.getMessage());
            }
            
            // 从请求体或查询参数中获取 user_accommodation_id
            String userAccommodationId = null;
            if (bodyMap != null && bodyMap.get("user_accommodation_id") != null) {
                userAccommodationId = bodyMap.get("user_accommodation_id").toString();
            } else {
                Map<String, String> query = service.readQuery(request);
                userAccommodationId = query.get("user_accommodation_id");
            }
            
            if (userAccommodationId == null || userAccommodationId.isEmpty()) {
                return error(400, "user_accommodation_id 不能为空");
            }

            // 查询住宿信息
            Map<String, String> accommodationQuery = new HashMap<>();
            accommodationQuery.put("user_accommodation_id", userAccommodationId);
            Map<String, String> accommodationConfig = new HashMap<>(); // 传递空配置而不是 null
            Query accommodationQueryResult = service.select(accommodationQuery, accommodationConfig);
            Object accommodationObj = accommodationQueryResult != null ? accommodationQueryResult.getSingleResult() : null;
            
            if (accommodationObj == null) {
                return error(404, "未找到住宿信息");
            }

            UserAccommodation accommodation;
            if (accommodationObj instanceof UserAccommodation) {
                accommodation = (UserAccommodation) accommodationObj;
            } else {
                return error(500, "数据格式错误");
            }

            // 获取用户手机号
            String phoneNumber = null;
            if (accommodation.getParticipants() != null) {
                Map<String, String> userQuery = new HashMap<>();
                userQuery.put("user_id", accommodation.getParticipants().toString());
                Query userQueryResult = userService.select(userQuery, null);
                Object userObj = userQueryResult != null ? userQueryResult.getSingleResult() : null;
                if (userObj instanceof User) {
                    User user = (User) userObj;
                    phoneNumber = user.getPhone();
                }
            }

            if (phoneNumber == null || phoneNumber.isEmpty()) {
                return error(400, "用户手机号为空，无法发送短信");
            }

            // 构建短信内容
            Map<String, String> smsParams = new HashMap<>();
            smsParams.put("conference_name", accommodation.getConference_name() != null ? accommodation.getConference_name() : "");
            smsParams.put("accommodation_location", accommodation.getAccommodation_location() != null ? accommodation.getAccommodation_location() : "");
            smsParams.put("accommodation_no", accommodation.getAccommodation_no() != null ? accommodation.getAccommodation_no() : "");
            smsParams.put("user_name", accommodation.getUser_name() != null ? accommodation.getUser_name() : "");

            // 发送短信
            Map<String, Object> smsResult = smsService.sendSms(phoneNumber, null, smsParams);
            String smsContent = smsService.buildNotificationContent("住宿", smsParams);
            smsResult.put("content", smsContent);

            log.info("发送住宿通知短信 - 手机号: {}, 内容: {}", phoneNumber, smsContent);

            return success(smsResult);
        } catch (Exception e) {
            log.error("发送住宿通知短信失败", e);
            return error(500, "发送短信失败: " + e.getMessage());
        }
    }

}
